package com.hos.operation.api;


import com.hos.db.entity.ArtEntity;
import com.hos.db.entity.SmsEntity;
import com.hos.db.entity.UserDocEntity;
import com.hos.db.entity.UserPatsEntity;
import com.hos.db.entity.consult.ConsultChatEntity;
import com.hos.db.entity.consult.ConsultDocEntity;
import com.hos.db.entity.msg.MsgEntity;
import com.hos.db.entity.relation.RelationEntity;
import com.hos.db.entity.visit.VisitEntityDoc;
import com.hos.db.manager.ArtManager;
import com.hos.db.manager.ConsultChatManager;
import com.hos.db.manager.ConsultManager;
import com.hos.db.manager.DocsManager;
import com.hos.db.manager.MsgManager;
import com.hos.db.manager.PatsManager;
import com.hos.db.manager.RelationManager;
import com.hos.db.manager.SMSManager;
import com.hos.db.manager.VisitsManager;
import com.hos.net.DictionariesFileService;
import com.hos.net.DictionariesIllService;
import com.hos.net.DictionariesPatService;
import com.hos.net.req.BaseReq;
import com.hos.net.req.UserSearchReq;
import com.hos.net.req.consult.ConsultChatAddReq;
import com.hos.net.req.consult.ConsultChatsReq;
import com.hos.net.req.consult.ConsultCreateReq;
import com.hos.net.req.consult.ConsultDeleteReq;
import com.hos.net.req.consult.ConsultIdReq;
import com.hos.net.req.consult.ConsultUpdateReq;
import com.hos.net.req.consult.ConsultUpdateStateReq;
import com.hos.net.req.consult.ConsultsReq;
import com.hos.net.req.pat.PatLoginReq;
import com.hos.net.req.pat.PatRegisterReq;
import com.hos.net.req.pat.PatRestPwdReq;
import com.hos.net.req.pat.PatUpdateReq;
import com.hos.net.req.pat.PatWXBoundReq;
import com.hos.net.req.pat.PatWXLoginReq;
import com.hos.net.req.push.PushReq;
import com.hos.net.req.relation.RelationDeleteReq;
import com.hos.net.req.relation.RelationReq;
import com.hos.net.req.sms.SmsReq;
import com.hos.net.req.sms.SmsVerifyReq;
import com.hos.net.req.visit.VisisReq;
import com.hos.net.res.BaseResponse;
import com.hos.net.res.MsgHint;
import com.hos.net.res.PageData;
import com.hos.net.res.loading.Upload7NRes;
import com.hos.operation.manager.ConstantData;
import com.hos.operation.manager.Yun7NManager;
import com.hos.utile.DLog;
import com.hos.utile.JsonUtile;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

@Controller
public class ApiPatController extends ApiBaseCommunal {

    @RequestMapping(value = "/pat", method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String app(HttpServletRequest request, @RequestBody String json) {
        BaseReq req = isVerifyDataJson(request, json,"pat");
        if (!req.isVerify) {
            return req.errorMsg;
        }
        //
        String service = req.service;
        String response = "";
        switch (service) {
            case DictionariesPatService.HOS_PAT_SMS_VERIFY:
                //验证码验证
                SmsVerifyReq smsVerifyReq = (SmsVerifyReq) JsonUtile.json2Obj(json, SmsVerifyReq.class);
                if (!smsVerifyReq.isVerifyParameter()) {
                    return smsVerifyReq.hint;
                }
                SmsEntity sms = SMSManager.getInstance().getSms(getJdbcTemplate(),
                        smsVerifyReq.phone, smsVerifyReq.type, smsVerifyReq.code);
                if (sms == null) {
                    response = new MsgHint("-1", "验证码无效").toJson();
                    DLog.e("没有发送验证码");
                    break;
                }
                //已经使用过了
                if (sms.isSmsIsVerifyIs()) {
                    response = new MsgHint("-1", "验证码无效").toJson();
                    DLog.e("已经使用过了");
                    break;
                }
                //超时
                long time = new Date().getTime() - sms.getSmsSendTime().getTime();
                if (time > ConstantData.SMS_OUT_TIME) {
                    response = new MsgHint("-1", "验证码无效").toJson();
                    SMSManager.getInstance().deleteSms(getJdbcTemplate(), sms.getSmsId());
                    DLog.e("验证码超时");
                    break;
                }
                //删除验证码
                SMSManager.getInstance().deleteSms(getJdbcTemplate(), sms.getSmsId());
                response = new MsgHint("0", "验证成功").toJson();
                break;

            case DictionariesPatService.HOS_PAT_SMS_REST_PWD:
                //患者重置密码发送验证码
                SmsReq smsReq = (SmsReq) JsonUtile.json2Obj(json, SmsReq.class);
                if (!smsReq.isVerifyParameter("4")) {
                    return smsReq.hint;
                }
                UserPatsEntity user = PatsManager.getInstance().getUserForPhone(getJdbcTemplate(), smsReq.phone);
                if (user == null) {
                    response = new MsgHint("-1", "该账号不存在").toJson();
                    break;
                }
                //发送验证码
                response = SMSManager.getInstance().smsSend(getJdbcTemplate(), smsReq);
                break;
            case DictionariesPatService.HOS_PAT_SMS_REG:
                //患者注册发送验证码
                smsReq = (SmsReq) JsonUtile.json2Obj(json, SmsReq.class);
                if (!smsReq.isVerifyParameter("3")) {
                    return smsReq.hint;
                }
                user = PatsManager.getInstance().getUserForPhone(getJdbcTemplate(), smsReq.phone);
                if (user != null) {
                    response = new MsgHint("-1", "该账号已经存在").toJson();
                    break;
                }
                //发送验证码
                response = SMSManager.getInstance().smsSend(getJdbcTemplate(), smsReq);
                break;
            case DictionariesPatService.HOS_PAT_SMS_WX_BOUND:
                //患者 微信 绑定手机号发送验证码
                smsReq = (SmsReq) JsonUtile.json2Obj(json, SmsReq.class);
                if (!smsReq.isVerifyParameter("5")) {
                    return smsReq.hint;
                }
                user = PatsManager.getInstance().getUserForPhone(getJdbcTemplate(), smsReq.phone);
                if (user != null) {
                    response = new MsgHint("-1", "该账手机号已经绑定过了").toJson();
                    break;
                }
                //发送验证码
                response = SMSManager.getInstance().smsSend(getJdbcTemplate(), smsReq);
                break;
            case DictionariesPatService.HOS_PAT_WX_LOGIN:
                //患者微信登录
                PatWXLoginReq patWXLoginReq = (PatWXLoginReq) JsonUtile.json2Obj(json, PatWXLoginReq.class);
                if (!patWXLoginReq.isVerifyParameter()) {
                    return patWXLoginReq.hint;
                }
                response = PatsManager.getInstance()
                        .userWXLoginReq(getJdbcTemplate(), patWXLoginReq);
                break;
            case DictionariesPatService.HOS_PAT_WX_BOUND:
                //患者微信 绑定手机号码
                UserPatsEntity pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                PatWXBoundReq patWXBoundReq = (PatWXBoundReq) JsonUtile.json2Obj(json, PatWXBoundReq.class);
                if (!patWXBoundReq.isVerifyParameter()) {
                    return patWXBoundReq.hint;
                }
                response = PatsManager.getInstance().updateWxBoundPhone(getJdbcTemplate(),
                        pat.getPatWXId(), patWXBoundReq.phone);
                break;
            case DictionariesPatService.HOS_PAT_REG:
                //注册
                PatRegisterReq regReq = (PatRegisterReq) JsonUtile.json2Obj(json, PatRegisterReq.class);
                if (!regReq.isVerifyParameter()) {
                    return regReq.hint;
                }
                response = PatsManager.getInstance().userRegisterReq(getJdbcTemplate(), regReq);
                break;
            case DictionariesPatService.HOS_PAT_LOGIN:
                //患者登录
                PatLoginReq patLoginReq = (PatLoginReq) JsonUtile.json2Obj(json, PatLoginReq.class);
                if (!patLoginReq.isVerifyParameter()) {
                    return patLoginReq.hint;
                }
                response = PatsManager.getInstance()
                        .userLoginReq(getJdbcTemplate(), patLoginReq.patAccount,
                                patLoginReq.patPwd, patLoginReq.pushId);
                break;
            case DictionariesPatService.HOS_PAT_REST_PWD:
                //患者重置密码
                PatRestPwdReq patRestPwdReq = (PatRestPwdReq) JsonUtile.json2Obj(json, PatRestPwdReq.class);
                if (!patRestPwdReq.isVerifyParameter()) {
                    return patRestPwdReq.hint;
                }
                response = PatsManager.getInstance()
                        .updateRestPwdReq(getJdbcTemplate(), patRestPwdReq.phone, patRestPwdReq.pwd);
                break;
            case DictionariesPatService.HOS_PAT_INFO_UPDATE:
                //患者 修改个人信息
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                PatUpdateReq patUpdateReq = (PatUpdateReq) JsonUtile.json2Obj(json, PatUpdateReq.class);
                patUpdateReq.patId = pat.getPatId();
                //
                response = PatsManager.getInstance()
                        .updateUserReq(getJdbcTemplate(), patUpdateReq);

                break;

            //================科普文章====================
            case DictionariesPatService.HOS_PAT_ARTS:
                List<ArtEntity> arts = ArtManager.getInstance().getIssueArts(getJdbcTemplate(),
                        req.pageNo, req.pageSize, true);
                int patSize = arts.size();
                BaseResponse baseRes = new BaseResponse();
                PageData pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    arts.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = arts.size();
                baseRes.pageData = pageData;
                baseRes.list = arts;
                response = JsonUtile.obj2Json(baseRes);
                break;
            //=================随访======================
            case DictionariesPatService.HOS_PAT_VISS:
                //获取
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                VisisReq visitsReq = (VisisReq) JsonUtile.json2Obj(json, VisisReq.class);
                //
                List<VisitEntityDoc> list = VisitsManager.getInstance().onDocVisitsReq(getJdbcTemplate(),
                        pat.getPatId(), visitsReq.isComplete, req.pageNo,
                        req.pageSize, true);
                patSize = list.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    list.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = list.size();
                baseRes.pageData = pageData;
                baseRes.list = list;
                response = JsonUtile.obj2Json(baseRes);
                break;
            //=================系统消息======================
            case DictionariesPatService.HOS_PAT_MSG:
                //获取系统消息
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                //
                List<MsgEntity> msgs = MsgManager.getInstance().onMsgsReq(getJdbcTemplate(),
                        "", pat.getPatId(), req.pageNo,
                        req.pageSize, true);
                patSize = msgs.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    msgs.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = msgs.size();
                baseRes.pageData = pageData;
                baseRes.list = msgs;
                response = JsonUtile.obj2Json(baseRes);
                break;
            //==========================咨询==============================================
            case DictionariesPatService.HOS_PAT_CONS:
                //咨询 列表
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultsReq consultsReq = (ConsultsReq) JsonUtile.json2Obj(json,
                        ConsultsReq.class);

                List<ConsultDocEntity> cons = ConsultManager.getInstance().onPatConsults(getJdbcTemplate(),
                        pat.getPatId(), consultsReq.type, req.pageNo,
                        req.pageSize, true);
                patSize = cons.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    cons.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = cons.size();
                baseRes.pageData = pageData;
                baseRes.list = cons;
                response = JsonUtile.obj2Json(baseRes);
                break;
            case DictionariesPatService.HOS_PAT_CON_ID:
                //获取咨询
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultIdReq consultIdReq = (ConsultIdReq) JsonUtile.json2Obj(json,
                        ConsultIdReq.class);
                if (!consultIdReq.isVerifyParameter()) {
                    return consultIdReq.hint;
                }
                response = ConsultManager.getInstance().onPatConsultsReq(getJdbcTemplate(),
                        consultIdReq.consultId);
                break;
            case DictionariesPatService.HOS_PAT_CONS_ADD:
                //咨询添加
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultCreateReq consultCreateReq = (ConsultCreateReq) JsonUtile.json2Obj(json,
                        ConsultCreateReq.class);
                if (!consultCreateReq.isVerifyParameter()) {
                    return consultCreateReq.hint;
                }
                response = ConsultManager.getInstance().onConsultAddReq(getJdbcTemplate(),
                        pat.getPatId(), consultCreateReq);
                break;
            case DictionariesPatService.HOS_PAT_CONS_UPDATE:
                //咨询 状态
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultUpdateReq consultUpdateReq = (ConsultUpdateReq) JsonUtile.json2Obj(json,
                        ConsultUpdateReq.class);
                if (!consultUpdateReq.isVerifyParameter()) {
                    return consultUpdateReq.hint;
                }
                response = ConsultManager.getInstance().onConsultUpdateReq(getJdbcTemplate(),
                        consultUpdateReq);
                break;
            case DictionariesPatService.HOS_PAT_CONS_DELETE:
                //咨询删除
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultDeleteReq consultDeleteReq = (ConsultDeleteReq) JsonUtile.json2Obj(json,
                        ConsultDeleteReq.class);
                if (!consultDeleteReq.isVerifyParameter()) {
                    return consultDeleteReq.hint;
                }
                response = ConsultManager.getInstance().onConsultDeleteReq(getJdbcTemplate(), consultDeleteReq.consultId);
                break;
            case DictionariesPatService.HOS_PAT_CONS_STATE:
                //咨询修改状态
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultUpdateStateReq consultUpdateStateReq = (ConsultUpdateStateReq) JsonUtile.json2Obj(json,
                        ConsultUpdateStateReq.class);
                if (!consultUpdateStateReq.isVerifyParameter()) {
                    return consultUpdateStateReq.hint;
                }
                response = ConsultManager.getInstance().onConsultUpdateReq(getJdbcTemplate(),
                        consultUpdateStateReq.consultId, consultUpdateStateReq.state);
                break;
            //==========================咨询聊天==============================================
            case DictionariesPatService.HOS_PAT_CON_CHATS:
                //咨询聊天
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultChatsReq consultChatsReq = (ConsultChatsReq) JsonUtile.json2Obj(json,
                        ConsultChatsReq.class);
                if (!consultChatsReq.isVerifyParameter()) {
                    return consultChatsReq.hint;
                }
                List<ConsultChatEntity> chats = ConsultChatManager.getInstance().onConsultChats(getJdbcTemplate(),
                        consultChatsReq.consultId, req.pageNo,
                        req.pageSize, true);
                patSize = chats.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    chats.remove(0);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = chats.size();
                baseRes.pageData = pageData;
                baseRes.list = chats;
                response = JsonUtile.obj2Json(baseRes);
                break;
            case DictionariesPatService.HOS_PAT_CON_CHAT_ADD:
                //咨询聊天添加
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                ConsultChatAddReq consultChatAddReq = (ConsultChatAddReq) JsonUtile.json2Obj(json,
                        ConsultChatAddReq.class);
                if (!consultChatAddReq.isVerifyParameter()) {
                    return consultChatAddReq.hint;
                }
                response = ConsultChatManager.getInstance().onConsultChatAddReq(getJdbcTemplate(),
                        consultChatAddReq);
                break;
            //==========================医患关系==============================================
            case DictionariesPatService.HOS_PAT_RELATION_QUERY:
                //查询关系状态
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                RelationReq relationReq = (RelationReq) JsonUtile.json2Obj(json,
                        RelationReq.class);
                if (!relationReq.isVerifyParameter()) {
                    return relationReq.hint;
                }
                RelationEntity entity = RelationManager.getInstance().onQuery(getJdbcTemplate(),
                        relationReq.docId, pat.getPatId());
                baseRes = new BaseResponse();
                baseRes.obj = entity;
                response = baseRes.toJson("0", "");
                break;
            case DictionariesPatService.HOS_PAT_RELATION_ADD:
                //添加关系
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                relationReq = (RelationReq) JsonUtile.json2Obj(json,
                        RelationReq.class);
                if (!relationReq.isVerifyParameter()) {
                    return relationReq.hint;
                }
                response = RelationManager.getInstance().onRelationAddReq(getJdbcTemplate(),
                        relationReq.docId, pat.getPatId());
                break;
            case DictionariesPatService.HOS_PAT_RELATION_DELETE:
                //删除关系
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                RelationDeleteReq relationDeleteReq = (RelationDeleteReq) JsonUtile.json2Obj(json,
                        RelationDeleteReq.class);
                if (!relationDeleteReq.isVerifyParameter()) {
                    return relationDeleteReq.hint;
                }
                response = RelationManager.getInstance().onRelationDeleteReq(getJdbcTemplate(),
                        relationDeleteReq.relationId);
                break;
            case DictionariesPatService.HOS_PAT_DOCS:
                //获取医生列表,搜索医生
                boolean isverify = verifyToken(req.token);
                if (!isverify) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                UserSearchReq docSearchReq = (UserSearchReq) JsonUtile.json2Obj(json, UserSearchReq.class);
                //
                List<UserDocEntity> docs = DocsManager.getInstance().getDocs(getJdbcTemplate(),
                        docSearchReq.key, false, req.pageNo, req.pageSize, true);
                patSize = docs.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    docs.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = docs.size();
                pageData.total = DocsManager.getInstance().getDocs(getJdbcTemplate(), docSearchReq.key);
                baseRes.pageData = pageData;
                baseRes.list = docs;
                response = JsonUtile.obj2Json(baseRes);
                break;
            case DictionariesPatService.HOS_PAT_RELATION_DOCS:
                //获取关系对应的医生
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                docs = RelationManager.getInstance().onDocs(getJdbcTemplate(),
                        pat.getPatId(), req.pageNo, req.pageSize, true);
                patSize = docs.size();
                baseRes = new BaseResponse();
                pageData = new PageData();
                if (patSize > req.pageSize) {
                    //有下一页
                    docs.remove(patSize - 1);
                    pageData.hasNextPage = true;
                }
                pageData.pageNo = req.pageNo;
                pageData.pageSize = docs.size();
                baseRes.pageData = pageData;
                baseRes.list = docs;
                response = JsonUtile.obj2Json(baseRes);
                break;
            //---------------推送id---------------------
            case DictionariesPatService.HOS_PAT_PUSH_ID:
                //上传推送id
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                PushReq pushReq = (PushReq) JsonUtile.json2Obj(json,
                        PushReq.class);
                String pushId = pushReq.pushId;
                response = PatsManager.getInstance().updatePushId(getJdbcTemplate(),
                        pat.getPatId(), pushId);
                break;
            //---------------文件上传token---------------------
            case DictionariesPatService.HOS_PAT_FILE_TOKEN:
                //获取7牛上传的token
                String token = Yun7NManager.getInstance().getToken();
                BaseResponse res = new BaseResponse();
                Upload7NRes upload7NRes = new Upload7NRes();
                upload7NRes.token = token;

                res.obj = upload7NRes;
                response = res.toJson("0", "获取上传凭证成功");
                break;
            default:
                pat = verifyTokenUser(req.token);
                if (pat == null) {
                    response = new MsgHint("100", "登陆过期，请重新登陆").toJson();
                    break;
                }
                if (DictionariesIllService.isIllService(service)) {
                    response = onIll(service, json, null, pat, null);
                    break;
                }
                if (DictionariesFileService.isUplaodingService(service)) {
                    response = onUploading(service, json, null, pat, null);
                    break;
                }
                response = new MsgHint("请求未定义").toJson();
                break;
        }
        return response;
    }

    //需要登陆才能操作
    private boolean verifyToken(String token) {
        return verifyTokenUser(token) != null;
    }

    private UserPatsEntity verifyTokenUser(String token) {
        return PatsManager.getInstance().verifyTokenUser(getJdbcTemplate(), token);
    }

}
